<script setup lang="ts">
import { ref } from 'vue';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Badge } from '@/components/ui/badge';
import { Plus, Edit, Trash2 } from 'lucide-vue-next';
import DynamicForm from '@/components/form/DynamicForm.vue';
import { createDictionaryFormSchema, editDictionaryFormSchema } from '@/components/form/schemas/dictionaryFormSchema';
import type { Dictionary } from '@/api/endpoints/system/dictionary';
import { createDictionary, updateDictionary, deleteDictionary } from '@/api/endpoints/system/dictionary';
import { toast } from '@/lib/toast';

interface Props {
  dictionaries: Dictionary[];
  selectedDictionary: Dictionary | null;
}

interface Emits {
  select: [dictionary: Dictionary];
  update: [];
}

defineProps<Props>();
const emit = defineEmits<Emits>();

const showCreateDialog = ref(false);
const showEditDialog = ref(false);
const editingDictionary = ref<Dictionary | null>(null);
const loading = ref(false);

// 创建字典
async function handleCreateDictionary(values: Record<string, any>) {
  loading.value = true;
  try {
    await createDictionary(values as any);
    toast.success('字典创建成功');
    emit('update');
    showCreateDialog.value = false;
  } catch (error) {
    toast.error('字典创建失败');
    console.error('创建字典失败:', error);
  } finally {
    loading.value = false;
  }
}

// 编辑字典
async function handleEditDictionary(values: Record<string, any>) {
  if (!editingDictionary.value) {
    return;
  }

  loading.value = true;
  try {
    await updateDictionary(editingDictionary.value.id, values);
    toast.success('字典更新成功');
    emit('update');
    showEditDialog.value = false;
    editingDictionary.value = null;
  } catch (error) {
    toast.error('字典更新失败');
    console.error('更新字典失败:', error);
  } finally {
    loading.value = false;
  }
}

// 删除字典
async function handleDeleteDictionary(dictionary: Dictionary) {
  try {
    await deleteDictionary(dictionary.id);
    toast.success('字典删除成功');
    emit('update');
  } catch (error) {
    toast.error('字典删除失败');
    console.error('删除字典失败:', error);
  }
}

// 打开编辑对话框
function openEditDialog(dictionary: Dictionary) {
  editingDictionary.value = dictionary;
  showEditDialog.value = true;
}

// 关闭编辑对话框
function closeEditDialog() {
  editingDictionary.value = null;
  showEditDialog.value = false;
}
</script>

<template>
  <div class="h-full flex flex-col">
    <!-- 头部 -->
    <div class="p-4 border-b border-border">
      <h2 class="text-lg font-semibold">
        字典管理
      </h2>
    </div>

    <!-- 工具栏 -->
    <div class="p-4">
      <Dialog v-model:open="showCreateDialog">
        <DialogTrigger as-child>
          <Button size="sm" class="w-full">
            <Plus class="w-4 h-4 mr-2" />
            新建字典
          </Button>
        </DialogTrigger>
        <DialogContent class="max-w-2xl">
          <DialogHeader>
            <DialogTitle>新建字典</DialogTitle>
          </DialogHeader>
          <DynamicForm
            :schema="createDictionaryFormSchema"
            :loading="loading"
            submit-button-text="创建"
            @submit="handleCreateDictionary"
            @cancel="showCreateDialog = false"
          />
        </DialogContent>
      </Dialog>
    </div>

    <!-- 字典列表 -->
    <div class="flex-1 overflow-y-auto">
      <div class="p-2 space-y-1">
        <div
          v-for="dictionary of dictionaries"
          :key="dictionary.id"
          class="group relative flex items-center justify-between p-3 rounded-lg cursor-pointer transition-colors hover:bg-muted/50"
          :class="{ 'bg-accent text-accent-foreground': selectedDictionary?.id === dictionary.id }"
          @click="emit('select', dictionary)"
        >
          <div class="flex-1 min-w-0">
            <div class="flex items-center gap-1">
              <h3 class="text-sm font-medium truncate">
                {{ dictionary.name }}
              </h3>
              <div class="text-xs text-muted-foreground">
                {{ dictionary.code }}
              </div>
            </div>

            <div class="mt-1">
              <Badge :variant="dictionary.status === 1 ? 'default' : 'secondary'" class="text-xs">
                {{ dictionary.status === 1 ? '启用' : '禁用' }}
              </Badge>
              <div v-if="dictionary.description" class="text-xs text-muted-foreground truncate">
                {{ dictionary.description }}
              </div>
            </div>
          </div>

          <!-- 操作按钮 -->
          <div class="flex items-center gap-1">
            <Button
              size="sm"
              variant="ghost"
              class="h-8 w-8 p-0"
              @click.stop="openEditDialog(dictionary)"
            >
              <Edit class="w-4 h-4" />
            </Button>
            <Button
              size="sm"
              variant="ghost"
              class="h-8 w-8 p-0 text-destructive hover:text-destructive"
              @click.stop="handleDeleteDictionary(dictionary)"
            >
              <Trash2 class="w-4 h-4" />
            </Button>
          </div>
        </div>
      </div>
    </div>

    <!-- 编辑字典对话框 -->
    <Dialog v-model:open="showEditDialog">
      <DialogContent class="max-w-2xl">
        <DialogHeader>
          <DialogTitle>编辑字典</DialogTitle>
        </DialogHeader>
        <DynamicForm
          v-if="editingDictionary"
          :schema="editDictionaryFormSchema"
          :initial-values="editingDictionary"
          :loading="loading"
          submit-button-text="更新"
          @submit="handleEditDictionary"
          @cancel="closeEditDialog"
        />
      </DialogContent>
    </Dialog>
  </div>
</template>
